package Lee_code;

import java.util.List;

class Lee_92 {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        // 使用虚拟节点
        ListNode dummyNode = new ListNode(-1);
        dummyNode.next = head;
        ListNode lNode = dummyNode;
        ListNode rightNode = dummyNode;
        // 找到lNode(反转部分的前一个)
        for (int i = 0; i < left - 1; i++) {
            lNode = lNode.next;
        }
        // 找到rightNode(反转部分中的最后一个)
        for (int i = 0; i < right-1; i++) {
            rightNode = rightNode.next;
        }
        // 切断节点
        ListNode rNode = rightNode.next;
        rightNode.next = null;
        ListNode leftNode = lNode.next;
        reverseLinkedList(leftNode);
        lNode.next = rightNode;
        leftNode.next = rNode;
        return dummyNode.next;
    }

    private void reverseLinkedList(ListNode head) {
        ListNode cur = head.next;
        ListNode pre = null;
        while (cur!=null){
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
    }
}
